package zsc.liangyi.blog.service.impl;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zsc.liangyi.blog.dao.ArticleDao;
import zsc.liangyi.blog.dao.CommentMapper;
import zsc.liangyi.blog.dao.StatisticMapper;
import zsc.liangyi.blog.model.ResponseData.StaticticsBo;
import zsc.liangyi.blog.model.domain.Article;
import zsc.liangyi.blog.model.domain.Comment;
import zsc.liangyi.blog.model.domain.Statistic;
import zsc.liangyi.blog.service.SiteService;

import java.util.List;

@Service
@Transactional
public class SiteServiceImpl implements SiteService {
    @Autowired
    private ArticleDao articleMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private StatisticMapper statisticMapper;

    //最新评论
    @Override
    public List<Comment> recentComments(int count) {
        //如果大于10条只显示10条，小于10条，有几条就显示几条
        PageHelper.startPage(1,count>10||count<1?10: count);

        List<Comment> commentList=commentMapper.selectNewComment();
        return commentList;
    }

    //最新发表的文章
    @Override
    public List<Article> recentArticles(int count) {
        PageHelper.startPage(1,count>10||count<1?10:count);
        List<Article> articleList=articleMapper.selectArticleWithPage();
        //封装文章统计信息
        Article article=null;
        Statistic statistic=null;
        Comment comment=null;
        for(int i=0;i<articleList.size();i++){
            article=articleList.get(i);
            statistic=statisticMapper.selectStatisticWithArticleId(article.getId());
            articleList.get(i).setHits(statistic.getHits());
            articleList.get(i).setCommentsNum(statistic.getCommentsNum());
        }
        return articleList;
    }

    //获取后台统计数据
    @Override
    public StaticticsBo getStatistics() {
        StaticticsBo staticticsBo=new StaticticsBo();
        Integer articles=articleMapper.countArticle();
        Integer comments=commentMapper.countComment();
        staticticsBo.setArticles(articles);
        staticticsBo.setComments(comments);
        return staticticsBo;
    }

    @Override
    public void updateStatistics(Article article) {
        Statistic statistic=statisticMapper.selectStatisticWithArticleId(article.getId());
        statistic.setHits(statistic.getHits()+1);
        statisticMapper.updateArticleHitsWithId(statistic);
    }
}
